//
//  BirthdayTableViewImplement.swift
//  FearfulNotification
//
//  Created by Jabin on 2019/5/28.
//  Copyright © 2019 筱鹏. All rights reserved.
//

import UIKit
import AudioToolbox

class BirthdayTableViewImplement: NSObject, UITableViewDelegate, UITableViewDataSource {
    let cellId = "BirthdayTableViewCellID"
    let headerID = "BirthdayViewControllerTableViewHeaderViewId"
    
    var tableView: UITableView!
    var entitys: [BirthdayEntity] = []
    weak var viewController: BaseViewController?
    
    var scrollActionUnlock: Bool = true
    var scrollActionOffset: CGFloat = -60
    
    convenience init(_ tableView: UITableView) {
        self.init()
        self.tableView = tableView
        setupTableView(tableView)
    }
    
    func setupTableView(_ tableView: UITableView) {
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = 68
        tableView.register(BirthdayTableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: headerID)
    }
    
    func setupViewController(_ viewController: BaseViewController) {
        self.viewController = viewController
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return entitys.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! BirthdayTableViewCell
        let entity = entitys[indexPath.row]
        cell.nameLabel.text = entity.name
        cell.birthdayLabel.text = String(format: "%02d-%02d", entity.birthdayMonth, entity.birthdayDay)
        cell.descLabel.text = entity.desc
        cell.alertSwitch.isOn = entity.alert
        cell.alertClosure = { [weak self] isOpen in
            entity.configAlertAndChangeStatus(isOpen, { (status) in
                if status != .correct {
                    // 直接reloadRow 有时会崩溃
                    self?.tableView.reloadData()
                }
                Event.message("status \(status)")
            })
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let edit = UITableViewRowAction(style: .normal, title: "Edit") { [weak self] (action, indexPath) in
            guard let ss = self else { return }
            guard let vc = ss.viewController else { return }
            let entity = ss.entitys[indexPath.row]
            BirthdayAppendViewController.present(fromVC: vc, birthdayId: entity.birthdayId)
        }
        let delete = UITableViewRowAction(style: .destructive, title: "Delete") { [weak self] (action, indexPath) in
            guard let ss = self else { return }
            let entity = ss.entitys[indexPath.row]
            entity.configAlertAndChangeStatus(false, { (status) in
                entity.execute.delete({ (success) in
                    ss.entitys.remove(at: indexPath.row)
                    ss.tableView.deleteRows(at: [indexPath], with: .automatic)
                })
            })
        }
        return [delete, edit]
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID)
        headerView?.textLabel?.text = "提示:向下滑动列表弹出菜单\n[注意所有数据均存在本地，应用删除数据将丢失]"
        headerView?.textLabel?.font = Theme.font.description
        headerView?.textLabel?.numberOfLines = 2
        return headerView
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollActionUnlock = true
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset
        if offset.y < scrollActionOffset && scrollActionUnlock {
            scrollActionUnlock = false
            userFeedBackOfVibrate()
        }
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let offset = scrollView.contentOffset
        if offset.y < scrollActionOffset {
            guard let vc = viewController else { return }
            SettingViewController.show(from: vc)
        }
    }
}

extension BirthdayTableViewImplement {
    
    func searchAll() {
        entitys = BirthdayEntity.execute.fetchAll("birthdayId", true)
        tableView.reloadData()
    }
    
}
